<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="description" content="PragmaticScala">
<meta name="generator" content="Paradox, paradox-material-theme=0.5.1, mkdocs-material=3.0.3">

<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="">
<meta name="lang:search.pipeline.stopwords" content="true">
<meta name="lang:search.pipeline.trimmer" content="true">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">


<meta name="description" content="PragmaticScala">
<link rel="shortcut icon" href="../assets/images/favicon.png">
<title>第6章——函数值和闭包 · </title>
<link rel="stylesheet" href="../assets/stylesheets/application.451f80e5.css">
<link rel="stylesheet" href="../lib/material__tabs/dist/mdc.tabs.min.css">
<link rel="stylesheet" href="../lib/prettify/prettify.css">
<script src="../assets/javascripts/modernizr.1aa3b519.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,400i,700|Roboto+Mono">
<style>
body,input{font-family:"Roboto","Helvetica Neue",Helvetica,Arial,sans-serif}
code,kbd,pre{font-family:"Roboto Mono","Courier New",Courier,monospace}
</style>
<link rel="stylesheet" href="../assets/fonts/font-awesome.css">
<link rel="stylesheet" href="../assets/fonts/material-icons.css">
<link rel="stylesheet" href="../assets/stylesheets/paradox-material-theme.css">
</head>
<body
>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer" autocomplete="off">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search" autocomplete="off">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="" class="md-header-nav__button md-logo">
<i class="md-icon">local_library</i>
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">
</span>
<span class="md-header-nav__topic">
第6章——函数值和闭包
</span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" name="search">
<input type="text" class="md-search__input" name="query" placeholder="Search" autocapitalize="off" autocorrect="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">&#xE5CD;</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>

</div>
</div>
</nav>
</header>

<div class="md-container">
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0" style="visibility: hidden">
<label class="md-nav__title md-nav__title--site" for="drawer">
<a href="../index.html" title="" class="md-nav__button md-logo">
<span class="md-nav__button md-logo">
<i class="md-icon">local_library</i>
</a>
<a href="../index.html" title="">
</a>
</label>
<ul>
  <li><a href="../contents.html" class="page">目录</a>
  <ul>
    <li><a href="../abstract.html" class="page">内容提要</a></li>
    <li><a href="../part1.html" class="page">第一部分 小试牛刀</a></li>
    <li><a href="../part2.html" class="page">第二部分 深入 Scala</a></li>
    <li><a href="../part3.html" class="page">第三部分 Scala 中的并发编程</a></li>
    <li><a href="../part4.html" class="page">第四部分 Scala 实战</a></li>
    <li><a href="../refs/references.html" class="page">参考书目</a></li>
    <li><a href="../extras.html" class="page">额外指引</a></li>
    <li><a href="../errata.html" class="page">勘误</a></li>
  </ul></li>
</ul>
<nav class="md-nav md-nav--secondary">
<label class="md-nav__title" for="__toc">Table of contents</label>
<ul>
  <li><a href="../chapter-06/index.html#第6章-函数值和闭包" class="header">第6章——函数值和闭包</a>
  <ul>
    <li><a href="../chapter-06/index.html#6-1-常规函数的局限性" class="header">6.1 常规函数的局限性</a></li>
    <li><a href="../chapter-06/index.html#6-2-可扩展性与高阶函数" class="header">6.2 可扩展性与高阶函数</a></li>
    <li><a href="../chapter-06/index.html#6-3-具有多个参数的函数值" class="header">6.3 具有多个参数的函数值</a></li>
    <li><a href="../chapter-06/index.html#6-4-柯里化" class="header">6.4 柯里化</a></li>
    <li><a href="../chapter-06/index.html#6-5-参数的占位符" class="header">6.5 参数的占位符</a></li>
    <li><a href="../chapter-06/index.html#6-6-参数路由" class="header">6.6 参数路由</a></li>
    <li><a href="../chapter-06/index.html#6-7-复用函数值" class="header">6.7 复用函数值</a></li>
    <li><a href="../chapter-06/index.html#6-8-部分应用函数" class="header">6.8 部分应用函数</a></li>
    <li><a href="../chapter-06/index.html#6-9-闭包" class="header">6.9 闭包</a></li>
    <li><a href="../chapter-06/index.html#6-10-execute-around-method-模式" class="header">6.10 Execute Around Method 模式</a></li>
  </ul></li>
</ul>
</nav>

</nav>
<ul style="display: none">
<li class="md-nav__item md-version" id="project.version">
<label class="md-nav__link" for="__version">
<i class="md-icon" title="Version">label_outline</i> 1.0.0
</label>
</li>
</ul>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<label class="md-nav__title" for="__toc">Table of contents</label>
<ul>
  <li><a href="../chapter-06/index.html#第6章-函数值和闭包" class="header">第6章——函数值和闭包</a>
  <ul>
    <li><a href="../chapter-06/index.html#6-1-常规函数的局限性" class="header">6.1 常规函数的局限性</a></li>
    <li><a href="../chapter-06/index.html#6-2-可扩展性与高阶函数" class="header">6.2 可扩展性与高阶函数</a></li>
    <li><a href="../chapter-06/index.html#6-3-具有多个参数的函数值" class="header">6.3 具有多个参数的函数值</a></li>
    <li><a href="../chapter-06/index.html#6-4-柯里化" class="header">6.4 柯里化</a></li>
    <li><a href="../chapter-06/index.html#6-5-参数的占位符" class="header">6.5 参数的占位符</a></li>
    <li><a href="../chapter-06/index.html#6-6-参数路由" class="header">6.6 参数路由</a></li>
    <li><a href="../chapter-06/index.html#6-7-复用函数值" class="header">6.7 复用函数值</a></li>
    <li><a href="../chapter-06/index.html#6-8-部分应用函数" class="header">6.8 部分应用函数</a></li>
    <li><a href="../chapter-06/index.html#6-9-闭包" class="header">6.9 闭包</a></li>
    <li><a href="../chapter-06/index.html#6-10-execute-around-method-模式" class="header">6.10 Execute Around Method 模式</a></li>
  </ul></li>
</ul>
</nav>

</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset">
<div class="md-content__searchable">
<h1><a href="#第6章-函数值和闭包" name="第6章-函数值和闭包" class="anchor"><span class="anchor-link"></span></a>第6章——函数值和闭包</h1>
<p>在函数式编程中，函数是一等公民。函数可以作为参数值传入其他函数中，函数的返回值可 以是函数，函数甚至可以嵌套函数。这些高阶函数在 Scala 中被称为函数值（function value）。闭 包（closure）是函数值的特殊形式，会捕获或者绑定到在另一个作用域或上下文中定义的变量。</p>
<h2><a href="#6-1-常规函数的局限性" name="6-1-常规函数的局限性" class="anchor"><span class="anchor-link"></span></a>6.1 常规函数的局限性</h2>
<blockquote>
  <p>FunctionValuesAndClosures/Sum.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">def sum(number: Int) = {
  var result = 0
  for (i ← 1 to number) {
    result += i
  }
  result
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/Sum.scala#L21-L27">Full source at GitHub</a>
<h2><a href="#6-2-可扩展性与高阶函数" name="6-2-可扩展性与高阶函数" class="anchor"><span class="anchor-link"></span></a>6.2 可扩展性与高阶函数</h2>
<blockquote>
  <p>FunctionValuesAndClosures/Loop.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">def totalResultOverRange(number: Int, codeBlock: Int ⇒ Int) = {
  var result = 0
  for (i ← 1 to number) {
    result += codeBlock(i)
  }
  result
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/Loop.scala#L21-L27">Full source at GitHub</a>
<blockquote>
  <p>FunctionValuesAndClosures/Loop.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">println(totalResultOverRange(11, i ⇒ i))</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/Loop.scala#L31">Full source at GitHub</a>
<blockquote>
  <p>FunctionValuesAndClosures/Loop.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">println(totalResultOverRange(11, i ⇒ if (i % 2 == 0) i else 0))</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/Loop.scala#L35">Full source at GitHub</a>
<blockquote>
  <p>FunctionValuesAndClosures/Loop.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">println(totalResultOverRange(11, i ⇒ if (i % 2 != 0) i else 0))</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/Loop.scala#L39">Full source at GitHub</a>
<h2><a href="#6-3-具有多个参数的函数值" name="6-3-具有多个参数的函数值" class="anchor"><span class="anchor-link"></span></a>6.3 具有多个参数的函数值</h2>
<blockquote>
  <p>FunctionValuesAndClosures/ZeroParam.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">def printValue(generator: () ⇒ Int): Unit = {
  println(s&quot;Generated value is ${generator()}&quot;)
}

printValue(() ⇒ 42)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/ZeroParam.scala#L21-L25">Full source at GitHub</a>
<blockquote>
  <p>FunctionValuesAndClosures/Inject.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">def inject(arr: Array[Int], initial: Int, operation: (Int, Int) ⇒ Int) = {
  var carryOver = initial
  arr.foreach(element ⇒ carryOver = operation(carryOver, element))
  carryOver
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/Inject.scala#L21-L25">Full source at GitHub</a>
<blockquote>
  <p>FunctionValuesAndClosures/Inject.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">val array = Array(2, 3, 5, 1, 6, 4)
val sum = inject(array, 0, (carry, elem) ⇒ carry + elem)
println(s&quot;Sum of elements in array is $sum&quot;)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/Inject.scala#L29-L31">Full source at GitHub</a>
<blockquote>
  <p>FunctionValuesAndClosures/Inject.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">val max =
  inject(array, Integer.MIN_VALUE, (carry, elem) ⇒ Math.max(carry, elem))
println(s&quot;Max of elements in array is  $max&quot;)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/Inject.scala#L35-L37">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">Sum of elements in array is 21
Max of elements in array is  6</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/output/Inject.output#L2-L3">Full source at GitHub</a>
<blockquote>
  <p>FunctionValuesAndClosures/Inject2.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">val sum = array.foldLeft(0)((sum, elem) ⇒ sum + elem) //可以被替换为对sum方法的调用
val max = array.foldLeft(Integer.MIN_VALUE) { (large, elem) ⇒
  Math.max(large, elem)
}

println(s&quot;Sum of elements in array is $sum&quot;)
println(s&quot;Max of elements in array is $max&quot;)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/Inject2.scala#L24-L30">Full source at GitHub</a>
<blockquote>
  <p>FunctionValuesAndClosures/Inject2.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">val sum = (0 /: array) { (sum, elem) ⇒ sum + elem }
val max =
  (Integer.MIN_VALUE /: array) { (large, elem) ⇒ Math.max(large, elem) }</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/Inject2.scala#L35-L37">Full source at GitHub</a>
<blockquote>
  <p>FunctionValuesAndClosures/Inject3.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">val sum = inject(array, 0) { (carryOver, elem) ⇒ carryOver + elem }</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/test/scala/chapter6/Inject3.scala#L29">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">Inject3.scala:9: error: not enough arguments for method inject: (arr:
Array[Int], initial: Int, operation: (Int, Int) =&gt; Int)Int.
Unspecified value parameter operation.
val sum = inject(array, 0) {(carryOver, elem) =&gt; carryOver + elem}
                ^
one error found</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/output/RunInject3.output#L2-L7">Full source at GitHub</a>
<h2><a href="#6-4-柯里化" name="6-4-柯里化" class="anchor"><span class="anchor-link"></span></a>6.4 柯里化</h2>
<pre class="prettyprint"><code class="language-output"><br/>scala&gt; def foo(a: Int)(b: Int)(c:Int) = {}
foo: (a: Int)(b: Int)(c: Int)Unit

scala&gt; foo _
res0: Int =&gt; (Int =&gt; (Int =&gt; Unit)) = &lt;function1&gt;

scala&gt; :quit</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/shoutput/RunMultipleParamsREPL.output#L2-L9">Full source at GitHub</a>
<blockquote>
  <p>FunctionValuesAndClosures/Inject4.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">def inject(arr: Array[Int], initial: Int)(operation: (Int, Int) ⇒ Int): Int = {
  var carryOver = initial
  arr.foreach(element ⇒ carryOver = operation(carryOver, element))
  carryOver
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/Inject4.scala#L21-L25">Full source at GitHub</a>
<blockquote>
  <p>FunctionValuesAndClosures/Inject4.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">val sum: Int = inject(array, 0) { (carryOver, elem) ⇒ carryOver + elem }</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/Inject4.scala#L31">Full source at GitHub</a>
<h2><a href="#6-5-参数的占位符" name="6-5-参数的占位符" class="anchor"><span class="anchor-link"></span></a>6.5 参数的占位符</h2>
<blockquote>
  <p>FunctionValuesAndClosures/Underscore.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">val arr = Array(1, 2, 3, 4, 5)

val total = (0 /: arr) { (sum, elem) ⇒ sum + elem }</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/Underscore.scala#L21-L23">Full source at GitHub</a>
<blockquote>
  <p>FunctionValuesAndClosures/Underscore.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">val total = (0 /: arr) { _ + _ }</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/Underscore.scala#L30">Full source at GitHub</a>
<blockquote>
  <p>FunctionValuesAndClosures/Underscore.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">val negativeNumberExists1 = arr.exists { elem ⇒ elem &lt; 0 }
val negativeNumberExists2 = arr.exists { _ &lt; 0 }</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/Underscore.scala#L37-L38">Full source at GitHub</a>
<h2><a href="#6-6-参数路由" name="6-6-参数路由" class="anchor"><span class="anchor-link"></span></a>6.6 参数路由</h2>
<blockquote>
  <p>FunctionValuesAndClosures/RouteParams.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">val largest =
  (Integer.MIN_VALUE /: arr) { (carry, elem) ⇒ Math.max(carry, elem) }</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/RouteParams.scala#L23-L24">Full source at GitHub</a>
<blockquote>
  <p>FunctionValuesAndClosures/RouteParams.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">val largest = (Integer.MIN_VALUE /: arr) { Math.max(_, _) }</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/RouteParams.scala#L31">Full source at GitHub</a>
<blockquote>
  <p>FunctionValuesAndClosures/RouteParams.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">val largest = (Integer.MIN_VALUE /: arr) { Math.max _ }</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/RouteParams.scala#L39">Full source at GitHub</a>
<blockquote>
  <p>FunctionValuesAndClosures/RouteParams.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">val largest = (Integer.MIN_VALUE /: arr) { Math.max }</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/RouteParams.scala#L47">Full source at GitHub</a>
<h2><a href="#6-7-复用函数值" name="6-7-复用函数值" class="anchor"><span class="anchor-link"></span></a>6.7 复用函数值</h2>
<blockquote>
  <p>FunctionValuesAndClosures/Equipment.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">class Equipment(val routine: Int ⇒ Int) {
  def simulate(input: Int): Int = {
    print(&quot;Running simulation...&quot;)
    routine(input)
  }
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/Equipment.scala#L20-L25">Full source at GitHub</a>
<blockquote>
  <p>FunctionValuesAndClosures/EquipmentUseNotDry.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">object EquipmentUseNotDry extends App {
  val equipment1 = new Equipment(
    { input ⇒ println(s&quot;calc with $input&quot;); input })
  val equipment2 = new Equipment(
    { input ⇒ println(s&quot;calc with $input&quot;); input })

  equipment1.simulate(4)
  equipment2.simulate(6)
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/EquipmentUseNotDry.scala#L20-L28">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">Running simulation...calc with 4
Running simulation...calc with 6</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/shoutput/RunEquipmentUseNotDry.output#L2-L3">Full source at GitHub</a>
<blockquote>
  <p>FunctionValuesAndClosures/EquipmentUseNotDry.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">object EquipmentUseDry extends App {
  val calculator = { input: Int ⇒ println(s&quot;calc with $input&quot;); input }

  val equipment1 = new Equipment(calculator)
  val equipment2 = new Equipment(calculator)

  equipment1.simulate(4)
  equipment2.simulate(6)
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/EquipmentUseDry.scala#L20-L28">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">Running simulation...calc with 4
Running simulation...calc with 6</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/shoutput/RunEquipmentUseDry.output#L2-L3">Full source at GitHub</a>
<blockquote>
  <p>FunctionValuesAndClosures/EquipmentUseNotDry2.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">object EquipmentUseDry2 extends App {
  def calculator(input: Int) = { println(s&quot;calc with $input&quot;); input }

  val equipment1 = new Equipment(calculator)
  val equipment2 = new Equipment(calculator)

  equipment1.simulate(4)
  equipment2.simulate(6)
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/EquipmentUseDry2.scala#L20-L28">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">Running simulation...calc with 4
Running simulation...calc with 6</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/shoutput/RunEquipmentUseDry2.output#L2-L3">Full source at GitHub</a>
<h2><a href="#6-8-部分应用函数" name="6-8-部分应用函数" class="anchor"><span class="anchor-link"></span></a>6.8 部分应用函数</h2>
<blockquote>
  <p>FunctionValuesAndClosures/Log.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">import java.util.Date

def log(date: Date, message: String): Unit = {
  //...
  println(s&quot;$date ---- $message&quot;)
}

val date = new Date(1420095600000L)
log(date, &quot;message1&quot;)
log(date, &quot;message2&quot;)
log(date, &quot;message3&quot;)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/Log.scala#L21-L31">Full source at GitHub</a>
<blockquote>
  <p>FunctionValuesAndClosures/Log.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">val date = new Date(1420095600000L)
val logWithDateBound = log(date, _: String)
logWithDateBound(&quot;message1&quot;)
logWithDateBound(&quot;message2&quot;)
logWithDateBound(&quot;message3&quot;)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/Log.scala#L36-L40">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">scala&gt; import java.util.Date
import java.util.Date

scala&gt; def log(date: Date, message: String) =  println(s&quot;$date ---- 
$message&quot;)
log: (date: java.util.Date, message: String)Unit

scala&gt; val logWithDateBound = log(new Date, _ : String)
logWithDateBound: String =&gt; Unit = &lt;function1&gt;

scala&gt; :quit</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/shoutput/RunREPL.output#L2-L12">Full source at GitHub</a>
<h2><a href="#6-9-闭包" name="6-9-闭包" class="anchor"><span class="anchor-link"></span></a>6.9 闭包</h2>
<blockquote>
  <p>FunctionValuesAndClosures/Closure.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">def loopThrough(number: Int)(closure: Int ⇒ Unit): Unit = {
  for (i ← 1 to number) { closure(i) }
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/Closure.scala#L21-L23">Full source at GitHub</a>
<blockquote>
  <p>FunctionValuesAndClosures/Closure.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">var result = 0
val addIt = { value: Int ⇒ result += value }</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/Closure.scala#L27-L28">Full source at GitHub</a>
<blockquote>
  <p>FunctionValuesAndClosures/Closure.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">loopThrough(10) { elem ⇒ addIt(elem) }
println(s&quot;Total of values from 1 to 10 is $result&quot;)

result = 0
loopThrough(5) { addIt }
println(s&quot;Total of values from 1 to 5 is $result&quot;)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/Closure.scala#L32-L37">Full source at GitHub</a>
<blockquote>
  <p>FunctionValuesAndClosures/Closure.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">var product = 1
loopThrough(5) { product *= _ }
println(s&quot;Product of values from 1 to 5 is $product&quot;)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/Closure.scala#L41-L43">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">Total of values from 1 to 10 is 55
Total of values from 1 to 5 is 15
Product of values from 1 to 5 is 120</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/output/Closure.output#L2-L4">Full source at GitHub</a>
<h2><a href="#6-10-execute-around-method-模式" name="6-10-execute-around-method-模式" class="anchor"><span class="anchor-link"></span></a>6.10 Execute Around Method 模式</h2>
<blockquote>
  <p>FunctionValuesAndClosures/Resource.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">class Resource private () {
  println(&quot;Starting transaction...&quot;)
  private def cleanUp(): Unit = { println(&quot;Ending transaction...&quot;) }
  def op1(): Unit = println(&quot;Operation 1&quot;)
  def op2(): Unit = println(&quot;Operation 2&quot;)
  def op3(): Unit = println(&quot;Operation 3&quot;)
}

object Resource {
  def use(codeBlock: Resource ⇒ Unit): Unit = {
    val resource = new Resource
    try {
      codeBlock(resource)
    } finally {
      resource.cleanUp()
    }
  }
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/Resource.scala#L21-L38">Full source at GitHub</a>
<blockquote>
  <p>FunctionValuesAndClosures/Resource.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">Resource.use { resource ⇒
  resource.op1()
  resource.op2()
  resource.op3()
  resource.op1()
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/Resource.scala#L42-L47">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">Starting transaction...
Operation 1
Operation 2
Operation 3
Operation 1
Ending transaction...</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/output/Resource.output#L2-L7">Full source at GitHub</a>
<blockquote>
  <p>FunctionValuesAndClosures/WriteToFile.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">import java.io._

def writeToFile(fileName: String)(codeBlock: PrintWriter ⇒ Unit): Unit = {
  val writer = new PrintWriter(new File(fileName))
  try { codeBlock(writer) } finally { writer.close() }
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/WriteToFile.scala#L21-L26">Full source at GitHub</a>
<blockquote>
  <p>FunctionValuesAndClosures/WriteToFile.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">writeToFile(&quot;output/output.txt&quot;) { writer ⇒
  writer write &quot;hello from Scala&quot;
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/WriteToFile.scala#L30-L32">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-txt">hello from Scala</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter6/output/output.txt#L2">Full source at GitHub</a>
</div>
<div>
<a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/master/src/paradox/chapter-06/index.md" title="Edit this page" class="md-source-file md-edit">
Edit this page
</a>
</div>
<div class="print-only">
<span class="md-source-file md-version">
1.0.0
</span>
</div>
</article>
</div>
</div>
</main>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="../part2.html" title="第二部分 深入 Scala" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span class="md-footer-nav__direction">
Previous
</span>
第二部分 深入 Scala
</span>
</div>
</a>
<a href="../chapter-07/index.html" title="第7章——特质" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span class="md-footer-nav__direction">
Next
</span>
第7章——特质
</span>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
Powered by
<a href="https://github.com/lightbend/paradox">Paradox</a>
and
<a href="https://jonas.github.io/paradox-material-theme/">Paradox Material Theme</a>

</div>
</div>
</div>
</footer>

</div>
<script src="../assets/javascripts/application.583bbe55.js"></script>
<script src="../assets/javascripts/paradox-material-theme.js"></script>
<script>app.initialize({version:"0.17",url:{base:"../."}})</script>
<script type="text/javascript" src="../lib/prettify/prettify.js"></script>
<script type="text/javascript" src="../lib/prettify/lang-scala.js"></script>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
window.prettyPrint && prettyPrint();
});
</script>
</body>
</html>
